package com.caineng.zhaobiao.zbapi.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.caineng.zhaobiao.zbapi.dao.CaiBaseUserDao;
import com.caineng.zhaobiao.zbapi.domain.CaiBaseUser;
import com.caineng.zhaobiao.zbapi.interceptor.logs.CainengApiLog;
import com.caineng.zhaobiao.zbapi.service.CainengApi;
import com.caineng.zhaobiao.zbapi.service.UserService;
import com.caineng.zhaobiao.zbapi.utils.AjaxResult;
import com.caineng.zhaobiao.zbapi.utils.RandomUserName;
import com.caineng.zhaobiao.zbapi.utils.StringUtils;
import com.caineng.zhaobiao.zbapi.utils.ZhaoBiaoCommon;
import com.caineng.zhaobiao.zbapi.utils.genID.IDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 用户登录信息类
 * @author liandyao
 * @date 2022/7/22 14:23
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("/zbapi/userLogin")
@Slf4j
public class UserLoginController {

    @Autowired
    CaiBaseUserDao userDao;

    @Autowired
    UserService userService;

    @Autowired
    private CainengApi cainengApi;


    @CainengApiLog(title = "手机号码登录")
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public AjaxResult login(String phone, String password){
        System.out.println("phone"+phone);
        Assert.notNull(phone,"手机号码不能为空");
        Assert.notNull(password,"密码不能为空");

        if(!StringUtils.isTruePhone(phone)){
            return AjaxResult.error("不是正确的手机号码");
        }
        return userService.login(phone,password) ;
    }

    @CainengApiLog(title = "手机号码注册")
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public AjaxResult register(CaiBaseUser user,String verifyCode){

        return userService.register(user,verifyCode) ;
    }

    @PostMapping("/logout")
    @ApiOperation(value = "用户注销登录")
    public AjaxResult logout(){
        StpUtil.logout();
        return AjaxResult.success("退出登录成功");
    }

    private final String errMsg = "服务器繁忙,请重启应用";

    /**
     * 一键登录,运营商提供一键登录功能
     * loginForPhoneOneYYS 该名字不能暴露,否则容易造成攻击
     * @param phone
     * @return
     */
    @CainengApiLog(title = "一键登录")
    @ApiIgnore
    @GetMapping("/loginForPhoneOneYYS")
    public AjaxResult loginForOnePlus(String phone) {
        log.info("用户名"+phone+"   ");

        if(StrUtil.isBlank(phone)){
            return AjaxResult.error("您输入的手机号码为空!");
        }
        if(!StringUtils.isTruePhone(phone)){
            return AjaxResult.error("输入手机号码错误");
        }

        CaiBaseUser user = userService.findUserByPhoneIgnoreDelFlag(phone);

        if (user == null) {
            //立即注册一个
            user = addUser(phone);
        }else if(user.getDelFlag()==ZhaoBiaoCommon.delFlag_YES){
            return AjaxResult.error(ZhaoBiaoCommon.DEL_FLAG_MSG);
        }
        //登录授权

        return userService.getAjaxResult(user);
    }

    private CaiBaseUser addUser(String phone){
        //如果没有就注册一个账号
        CaiBaseUser user = new CaiBaseUser();
        user.setId(IDUtils.getID());
        user.setShowName(RandomUserName.getUserName());
        user.setPhone(phone);
        user.setCreateTime(DateUtil.now());
        userDao.insert(user);
        return user;
    }

    /**
     * 微信用户信息
     */
    @Data
    private class WeixinUser{
        private String openId ;
        private String nickName ;
        private String avatarUrl ;
        private String unionId ;
    }

    @CainengApiLog(title = "app微信登录")
    @ApiOperation(value = "微信登录")
    @PostMapping("/loginByWeixin")
    public AjaxResult loginByWeixin(WeixinUser user) {

        String unionId = user.getUnionId(); //唯一编号,可以和小程序一起使用
        CaiBaseUser userUnion=userService.findUserByUnionid(unionId);
        log.info("微信登录唯一ID:"+unionId+"  ===>"+ JSONUtil.toJsonStr(userUnion));
        if (userUnion == null) { //直接注册一个人
            userUnion = new CaiBaseUser();
            userUnion.setId(IDUtils.getID());
            userUnion.setUnionid(user.getUnionId());
            userUnion.setOpenid(user.getOpenId());
            userUnion.setShowName(user.getNickName());
            userUnion.setHeadImg(user.getAvatarUrl());
            userUnion.setCreateTime(DateUtil.now());
            userDao.insert(userUnion); //加入数据库
        }else if(userUnion.getDelFlag()==2){
            return AjaxResult.error(ZhaoBiaoCommon.DEL_FLAG_MSG);
        }
        return userService.getAjaxResult(userUnion);
    }


    @GetMapping("/checkSms")
    public AjaxResult checkSms(String phone,String code){
        AjaxResult res = cainengApi.checkSMS(phone,code);
        if(AjaxResult.OK_CODE.equals(res.getCode())){
            return AjaxResult.success("验证码正确");
        }else{
            return AjaxResult.error(res.getMsg());
        }
    }

    @CainengApiLog(title = "苹果账号登录")
    @ApiOperation(value = "苹果账号登录")
    @PostMapping("/iosLogin")
    public AjaxResult iosLogin(String access_token,String openid){
        log.info("====>"+access_token+"   "+openid);
        //苹果登录授权
        if(StrUtil.isBlank(access_token) || StrUtil.isBlank(openid)){
            return AjaxResult.error("参数不正确");
        }
        //是否已经存在用户

        CaiBaseUser user = userService.findUserByIosIdCache(openid);
        if(user==null){
            return AjaxResult.success("请绑定手机!",1);
        }else{
            if(user!=null && user.getDelFlag()==ZhaoBiaoCommon.delFlag_YES){
                return AjaxResult.error(ZhaoBiaoCommon.DEL_FLAG_MSG);
            }
            if(StrUtil.isBlank(user.getPhone())){
                return AjaxResult.success("请绑定手机!",1);
            }
            return userService.getAjaxResult(user);
        }
    }


    /**
     * 苹果登录
     */
    @ApiOperation(value = "苹果绑定手机号码")
    @PostMapping("/bindingIOS")
    public AjaxResult bindingIOS(String verifyCode, String iosId, String phone) {
        if(!StringUtils.isTruePhone(phone)){
            return AjaxResult.error("注册失败,手机号码为空!");
        }
        AjaxResult result = checkSms(phone, verifyCode);
        if (result.getCode().equals("500")) {
            return result;
        }
        CaiBaseUser bgUser = userService.findUserByPhoneIgnoreDelFlag(phone);
        if(bgUser!=null && bgUser.getDelFlag()==ZhaoBiaoCommon.delFlag_YES){
            return AjaxResult.error(ZhaoBiaoCommon.DEL_FLAG_MSG);
        }
        if (bgUser == null) {

            CaiBaseUser user = new CaiBaseUser();
            user.setId(IDUtils.getID());
            user.setShowName(RandomUserName.getUserName());
            user.setPhone(phone);
            user.setCreateTime(DateUtil.now());
            user.setIosId(iosId);
            userDao.insert(user);

            return userService.getAjaxResult(user);
        } else {
            bgUser.setIosId(iosId);
            userDao.save(bgUser);
            return userService.getAjaxResult(bgUser);
        }
    }



}
